package api

import (
	"multitude-cloud-exporter/pkg/cache"
	"multitude-cloud-exporter/pkg/resource"
	"multitude-cloud-exporter/pkg/resource/common"

	"github.com/gin-gonic/gin"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

type Api struct{}

func (a *Api) GetResourceMetrics() gin.HandlerFunc {
	return func(c *gin.Context) {
		//TODO 整理每种类型请求所需要的参数

		//TODO 参数校验

		queryMap := c.QueryMap("labels")
		if value, ok := c.GetQuery("zero_id"); ok {
			queryMap["zero_id"] = value
		}
		if value, ok := c.GetQuery("project_id"); ok {
			queryMap["project_id"] = value
		}

		//TODO 设置统一规范Key
		cloud := c.DefaultQuery("cloud", "self")
		ctype := c.DefaultQuery("cloud_type", "self")
		regionId := c.DefaultQuery("region_id", "00")
		resoucrceId := c.DefaultQuery("cloud_id", "00")
		resoucrceName := c.DefaultQuery("name", "self")
		key := cloud + ":" + ctype + ":" + regionId

		rt, found := cache.Global.Get(key)
		if !found {
			rt = cache.New()
			cache.Global.Set(key, rt)
			resource.BatchUpdateMetrics(key, cloud, ctype, regionId, queryMap)
		}
		//
		rcache, ok := rt.(cache.Cache)
		if !ok {
			return
		}
		//
		r, found := rcache.Get(resoucrceId)
		var re common.Resource
		if !found {
			re, err := resource.NewResource(resoucrceName, resoucrceId, cloud, ctype, regionId, queryMap)
			if err != nil {
				return
			}
			//re.UpdateMetrics()
			rcache.Set(resoucrceId, re)
		} else {
			re = r.(common.Resource)
			//re.UpdateMetrics()
		}

		//TODO 调用接口获取 更新该资源下的指标 与定时同步避让策略？？
		promhttp.HandlerFor(
			re.GetRegistry(),
			promhttp.HandlerOpts{}).
			ServeHTTP(c.Writer, c.Request)
	}
}
